import { prisma } from "@/lib/prisma"
import { ReturnList } from "@/components/returns/return-list"
import { ReturnHeader } from "@/components/returns/return-header"
import { Metadata } from "next"
import { ReturnRecords } from "@/components/returns/return-records"
import { SerializedSale, SerializedReturn } from '@/types'

export const metadata: Metadata = {
  title: "退货管理 - 商场销售系统",
  description: "退货管理页面",
}

export default async function ReturnsPage() {
  // 获取销售单和退货记录
  const [sales, returns] = await Promise.all([
    prisma.sale.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        items: {
          include: { product: true }
        }
      }
    }),
    prisma.returnOrder.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        sale: true,
        items: {
          include: {
            product: true,
            saleItem: true
          }
        }
      }
    })
  ])

  // 序列化数据
  const serializedData: {
    sales: SerializedSale[]
    returns: SerializedReturn[]
  } = {
    sales: sales.map(sale => ({
      ...sale,
      totalAmount: sale.totalAmount.toString(),
      createdAt: sale.createdAt.toISOString(),
      updatedAt: sale.updatedAt.toISOString(),
      items: sale.items.map(item => ({
        ...item,
        saleItemId: item.id,
        price: item.price.toString(),
        amount: item.amount.toString(),
        product: {
          ...item.product,
          price: item.product.price.toString()
        }
      }))
    })),
    returns: returns.map(returnOrder => ({
      ...returnOrder,
      totalAmount: returnOrder.totalAmount.toString(),
      createdAt: returnOrder.createdAt.toISOString(),
      updatedAt: returnOrder.updatedAt.toISOString(),
      sale: {
        ...returnOrder.sale,
        totalAmount: returnOrder.sale.totalAmount.toString(),
        createdAt: returnOrder.sale.createdAt.toISOString(),
        updatedAt: returnOrder.sale.updatedAt.toISOString()
      },
      items: returnOrder.items.map(item => ({
        ...item,
        price: item.price.toString(),
        amount: item.amount.toString(),
        product: {
          ...item.product,
          price: item.product.price.toString()
        },
        saleItem: {
          ...item.saleItem,
          price: item.saleItem.price.toString(),
          amount: item.saleItem.amount.toString()
        }
      }))
    }))
  }

  // 计算每个销售单明细的已退货数量
  const returnedItems: Record<number, number> = {}
  returns.forEach(returnOrder => {
    returnOrder.items.forEach(item => {
      returnedItems[item.saleItemId] = (returnedItems[item.saleItemId] || 0) + item.quantity
    })
  })

  return (
    <div className="space-y-8 p-8">
      {/* 退货记录列表 */}
      <ReturnRecords returns={serializedData.returns} />

      {/* 可退货的销售单列表 */}
      <div>
        <h2 className="text-lg font-medium text-gray-900 mb-4">销售单列表</h2>
        <ReturnList sales={serializedData.sales} returnedItems={returnedItems} />
      </div>
    </div>
  )
} 